package cn.yanhu.kuwanapp.my.activity

import android.content.Context
import android.content.Intent
import android.text.TextUtils
import android.view.View
import androidx.lifecycle.Observer
import cn.woochen.comlib.BaseActivity
import cn.woochen.comlib.util.OnSingleClickListener
import cn.woochen.comlib.util.SystemAppUtil
import cn.woochen.comlib.util.ext.setOnSingleClickListener
import cn.yanhu.kuwanapp.R
import cn.yanhu.kuwanapp.databinding.ActivityPersonInfoBinding
import cn.yanhu.kuwanapp.event.AccountAuthEvent
import cn.yanhu.kuwanapp.http.status.ErrorCode
import cn.yanhu.kuwanapp.user.UserViewModel
import cn.yanhu.kuwanapp.utils.AlipayUtil
import cn.yanhu.kuwanapp.utils.AuthResult
import cn.yanhu.kuwanapp.utils.ext.logcom
import cn.yanhu.kuwanapp.utils.ext.parseState
import cn.yanhu.kuwanapp.utils.ext.parseState2
import cn.yanhu.kuwanapp.utils.ext.showToast
import cn.yanhu.kuwanapp.utils.third.AccountReqType
import cn.yanhu.kuwanapp.utils.third.AccountType
import cn.yanhu.kuwanapp.utils.third.ThirdAccountHelper
import com.alipay.sdk.app.AuthTask
import com.jeremyliao.liveeventbus.LiveEventBus
import kotlin.concurrent.thread

/**
 * 类描述：个人中心
 * @author：woochen
 * create at：2021/8/6 10:51 PM
 */
class PersonInfoActivity : BaseActivity<ActivityPersonInfoBinding, UserViewModel>(),
    OnSingleClickListener {

    override fun setContentView(): Int = R.layout.activity_person_info

    override fun initData() {
        setStatusBarStyle(false)
    }

    override fun onStart() {
        super.onStart()
        requestData()
    }

    override fun initListener() {
        mBinding.rlNickname.setOnSingleClickListener(this)
        mBinding.tvBindAlipay.setOnSingleClickListener(this)
        mBinding.tvBindWx.setOnSingleClickListener(this)
    }

    private var alipayBindStatus = ""
    private var alipayAuthResult: AuthResult? = null

    override fun registerNecessaryObserver() {
        super.registerNecessaryObserver()
        //我的页面
        mViewModel.userInfoInfo.observe(this, Observer { it ->
            parseState(it, {
                mBinding.userInfo = it
            })
        })
        //微信授权码获取成功
        LiveEventBus.get(AccountAuthEvent::class.java).observe(this, Observer {
            val wxCode = it.code ?: ""
            mViewModel.wxAuth(wxCode, "2")
        })
        //微信授权成功
        mViewModel.wxAuthInfo.observe(this, Observer { it ->
            parseState(it, {
                requestData()
            })
        })
        //绑定支付宝
        mViewModel.bindAlipayInfo.observe(this, Observer { it ->
            parseState(it, { data ->
                val map = AlipayUtil.buildAuthInfoMap(data) ?: hashMapOf()
                val param: String? = AlipayUtil.buildOrderParam(map)
                logcom("$param")
                thread {
                    // 构造AuthTask 对象
                    val authTask = AuthTask(mContext)
                    // 调用授权接口，获取授权结果
                    val result: Map<String, String> = authTask.authV2(param, true)
                    runOnUiThread {
                        alipayAuthResult = AuthResult(result, true)
                        alipayBindStatus = alipayAuthResult?.resultStatus ?: ""
                        val result: String = alipayAuthResult?.result ?: ""
                        mViewModel.bindAlipayCallBack(result)
                    }
                }
            })
        })
        //支付宝绑定回调
        mViewModel.bindAlipayCallBackInfo.observe(this, Observer { it ->
            parseState2(it, {
                // 判断resultStatus 为“9000”且result_code
                // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                if (TextUtils.equals(alipayBindStatus, "9000"
                    ) && TextUtils.equals(alipayAuthResult?.resultCode, "200")
                ) {
                    // 获取alipay_open_id，调支付时作为参数extern_token 的value
                    // 传入，则支付账户为该授权账户
                    // showAlert(PayDemoActivity.this, getString(R.string.auth_success) + authResult);
                    showToast("授权成功")
                    requestData()
                } else {
                    // 其他状态值则为授权失败
                    showToast("授权失败")
                }
            })
        })
    }

    companion object {

        fun start(context: Context) {
            val intent = Intent(context, PersonInfoActivity::class.java)
            context.startActivity(intent)
        }
    }

    override fun requestData() {
        mViewModel.userInfo("1")
    }

    override fun onSingleClick(v: View?) {
        when (v) {
            mBinding.rlNickname -> { //修改昵称
                EditNicknameActivity.start(mContext, mBinding.userInfo?.nickName ?: "")
            }
            mBinding.tvBindAlipay -> { //绑定支付宝
                bindAlipay()
            }
            mBinding.tvBindWx -> { //绑定微信
                ThirdAccountHelper.sendAuthReq(AccountType.WX, AccountReqType.Auth)
            }
        }
    }

    /**
     * 绑定支付宝
     */
    private fun bindAlipay() {
        if (!SystemAppUtil.isAliPayInstalled(mContext)) {
            showToast("请先安装支付宝")
            return
        }
        mViewModel.bindAlipay()
    }
}